package service

import (
	"fmt"
	"illuminant/model"
	"illuminant/util"
)

const gqlAddFile = `mutation add_file($id: uuid!, $filename: String!, $filepath: String!) {
  insert_illuminant_file_one(object: {id: $id, filename: $filename, filepath: $filepath}) {
    id
    filename
    filepath
  }
}`

const gqlGetFileByID = `query get_file($id: uuid!){
  illuminant_file_by_pk(id: $id) {
    id
    filename
    filepath
    status
  }
}`

const gqlDeleteFileByID = `mutation delete_item_by_pk($id: uuid!) {
  delete_illuminant_file_by_pk(id: $id) {
    id
    filename
    filepath
  }
}`

const gqlRefreshFileStatusByID = `mutation update_item_by_pk($id: uuid!, $status: Int) {
  update_illuminant_file_by_pk(pk_columns: {id: $id}, _set: { status: $status }) {
    id
  }
}`

func AddFile(id, fn, fp string) error {
	var data struct {
		File *model.IlluminantFile `json:"insert_illuminant_file_one"`
	}

	params := map[string]interface{}{
		"id":       id,
		"filename": fn,
		"filepath": fp,
	}

	err := util.Graphql(gqlAddFile, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return err
	}

	return nil
}

func GetFileByID(id string) (*model.IlluminantFile, error) {
	var data struct {
		File *model.IlluminantFile `json:"illuminant_file_by_pk"`
	}

	params := map[string]interface{}{
		"id": id,
	}

	err := util.Graphql(gqlGetFileByID, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil, err
	}

	return data.File, nil
}

func DeleteFileByID(id string) (*model.IlluminantFile, error) {
	var data struct {
		File *model.IlluminantFile `json:"delete_illuminant_file_by_pk"`
	}

	params := map[string]interface{}{
		"id": id,
	}

	err := util.Graphql(gqlDeleteFileByID, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil, err
	}

	return data.File, nil
}

func RefreshFileStatusByID(id string, status int) (*model.IlluminantFile, error) {
	var data struct {
		File *model.IlluminantFile `json:"update_illuminant_file_by_pk"`
	}

	params := map[string]interface{}{
		"id":     id,
		"status": status,
	}

	err := util.Graphql(gqlRefreshFileStatusByID, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil, err
	}

	return data.File, nil
}
